package com.xiaohang.springstudy.chapter1.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.xiaohang.springstudy.chapter1.config.MyX509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpsUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
    public static final String KEY = "key";
    public static final String VALUE = "value";

    /**
     * 返回string 测试用
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = null;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return buffer != null ? buffer.toString() : null;
    }

    /**
     * 返回list 处理https GET/POST请求 请求地址、请求方法、参数
     */
    public static List httpsRequestList(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer;
        List list = new ArrayList();
        try {
            // 创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            // 初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            if (buffer.length() > 0) {
                String datestr = buffer.toString();
                Map<String, Object> jb = JSONObject.parseObject(datestr, Map.class);
                if (null != jb.get("data")) {
                    if (jb.get("data") instanceof List) {
                        list = (List) jb.get("data");
                    }
                }
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 返回list 处理https GET/POST请求 请求地址、请求方法、参数
     */
    public static Map httpsRequestMap(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer;
        Map map = new HashMap();
        try {
            // 创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            // 初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            if (buffer.length() > 0) {
                String datestr = buffer.toString();
                JSONObject jb = JSONObject.parseObject(datestr, Feature.IgnoreNotMatch);
                if (null != jb.get("data")) {
                    if (jb.get("data") instanceof Map) {
                        map = (Map) jb.get("data");
                    }
                } else if (jb instanceof Map) {
                    map = jb;
                }
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 返回boolean
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     */
    public static boolean httpsRequestBoolean(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer;
        boolean bool = false;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            if (buffer.length() > 0) {
                String datestr = buffer.toString();
                JSONObject jb = JSONObject.parseObject(datestr);
                bool = (boolean) jb.get("data");
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 返回file io 流
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     */
    public static InputStream httpsRequestFile(String requestUrl, String requestMethod, String outputStr) {
        InputStream InputStr = null;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStr = conn.getInputStream();

        } catch (Exception e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return InputStr;
    }

    /**
     * 对传递的参数进行封装map
     *
     * @param map
     * @return
     */
    public static String postpar(Map<String, String> map) {
        //请求参数获取
        String postpar = "";
        // map格式的请求参数
        if (map != null) {
            StringBuffer mstr = new StringBuffer();
            for (String str : map.keySet()) {
                String val = map.get(str);
                try {
                    val = URLEncoder.encode(val, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    logger.debug(e.getMessage());
                    e.printStackTrace();
                }
                mstr.append(str + "=" + val + "&");
            }
            // 最终参数
            postpar = mstr.toString();
            int lasts = postpar.lastIndexOf("&");
            postpar = postpar.substring(0, lasts);
        }
        return postpar;
    }

    public static String postJson(Map<String, String> map) {
        // 请求参数获取
        String postpar = "";
        // map格式的请求参数
        if (map != null) {
            StringBuffer mstr = new StringBuffer();
            for (String str : map.keySet()) {
                String val;
                val = JSON.toJSONString(map.get(str));
                mstr.append('"' + str + '"' + ":" + val + ",");
            }
            // 最终参数
            postpar = mstr.toString();
            int lasts = postpar.lastIndexOf(",");
            postpar = postpar.substring(0, lasts);
            postpar = "{" + postpar + "}";
            try {
                postpar = URLEncoder.encode(postpar, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.debug(e.getMessage());
                e.printStackTrace();
            }
        }
        return postpar;
    }

    //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    //1.获取返回值list
    public static List reultList(String args, String url) throws Exception {
        JSONObject jsonObject = JSON.parseObject(args);
        Map<String, String> map = new HashMap<>();
        for (Object obj : jsonObject.keySet()) {
            map.put(obj.toString(), jsonObject.get(obj).toString());
        }
        map.put("timestamp", System.currentTimeMillis() + "");
        map.put("sign", SecurityUtil.getSignJson(KEY, VALUE, map));
        return httpsRequestList(url + "?" + postpar(map), "GET", null);
    }

    //1.1获取返回值list
    public static List reultList(Map<String, String> map, String url) throws Exception {
        map.put("timestamp", System.currentTimeMillis() + "");
        String sign = SecurityUtil.getSign(KEY, VALUE, map);
        map.put("sign", sign);
        return httpsRequestList(url + "?" + postpar(map), "GET", null);
    }

    //2.获取返回值map
    public static Map reultMap(Map<String, String> map, String url) throws Exception {
        map.put("timestamp", System.currentTimeMillis() + "");
        String sign = SecurityUtil.getSign(KEY, VALUE, map);
        map.put("sign", sign);
        return httpsRequestMap(url + "?" + postpar(map), "GET", null);
    }

    /**
     * 功能描述: 微信小程序获取接口数据
     *
     * @param: [map, url]
     * @return: java.util.Map
     * @auther: lanyuansong
     * @date: 2018/11/29 10:07
     */
    public static List wxreultList(Map<String, String> map, String url) throws Exception {
        map.put("timestamp", System.currentTimeMillis() + "");
        String sign = SecurityUtil.getSign(KEY, VALUE, map);
        map.put("sign", sign);
        return httpsRequestList(url + "?" + postpar(map), "GET", null);

    }

    /**
     * 功能描述: 微信小程序获取接口数据
     *
     * @param: [map, url]
     * @return: java.util.Map
     * @auther: lanyuansong
     * @date: 2018/11/29 10:07
     */
    public static Map wxreultMap(Map<String, String> map, String url) throws Exception {

        map.put("timestamp", System.currentTimeMillis() + "");
        String sign = SecurityUtil.getSign(KEY, VALUE, map);
        map.put("sign", sign);
        return httpsRequestMap(url + "?" + postpar(map), "GET", null);
    }

    //3.获取返回值boolean值
    public static boolean reultBoolean(String args, String url) throws Exception {
        JSONObject jsonObject = JSON.parseObject(args);
        Map<String, String> map = new HashMap<>();
        for (Object obj : jsonObject.keySet()) {
            map.put(obj.toString(), jsonObject.get(obj).toString());
        }
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("sign", SecurityUtil.getSignJson(KEY, VALUE, map));
        return httpsRequestBoolean(url + "?" + postpar(map), "GET", null);
    }

    //4.获取返回值File 流  InputStream InputStr
    public static String reultInputStream(String proIdSecret, String bodyType, String docId, String url) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("proIdSecret", proIdSecret);
        map.put("bodyType", bodyType);
        map.put("docId", docId);
        map.put("timestamp", System.currentTimeMillis() + "");
        map.put("sign", SecurityUtil.getSignJson(KEY, VALUE, map));
        return url + "?" + postpar(map);
    }

    //5.获取返回值String
    public static String reultStr(Map<String, String> map, String url) throws Exception {
        map.put("timestamp", System.currentTimeMillis() + "");
        map.put("sign", SecurityUtil.getSign(KEY, VALUE, map));
        return httpsRequest(url + postpar(map), "GET", null);
    }

    //5.获取返回值String(入参json)
    public static String reultStrByJson(Map<String, String> map, String url) throws Exception {
        map.put("timestamp", System.currentTimeMillis() + "");
        map.put("sign", SecurityUtil.getSignJson(KEY, VALUE, map));
        return httpsRequest(url + postJson(map), "GET", null);
    }


    public static void main(String[] args) throws Exception {
        String url = "https://njdev.jfh.com/jftender/saveOrderEvaluationNew?cooperateMark=null&operateFlg=1&teamMark=4&recommendMark=4&platformBodyType=1&totalMark=5&serviceMark=4&updateTime=2018-09-07+16%3A12%3A40.0&userId=3111&businessMark=null&content=&isShow=N&token=2F41E91F14E87BB7C907972FA9FFC41A&platformProjectId=134&serialVersionUID=1&qualityMark=5&createBy=%E9%A9%AC%E6%98%8E&checkTime=2018-09-03+04%3A50%3A27.0&createTime=2018-09-07+16%3A12%3A07.0&updateBy=%E9%A9%AC%E6%98%8E&progressMark=4&id=29a6d45e9e0a45d68ae44594ea2a0835&userType=1&evaluateNum=4";
//		String url = "https://njdev.jfh.com/jftender/saveOrderEvaluationNew?cooperateMark=null&operateFlg=0&teamMark=4&recommendMark=4&platformBodyType=1&totalMark=5&serviceMark=4&updateTime=2018-09-07 16:12:40.0&userId=3111&businessMark=null&content=&isShow=N&token=2F41E91F14E87BB7C907972FA9FFC41A&platformProjectId=134&serialVersionUID=1&qualityMark=5&createBy=马明&checkTime=2018-09-03 04:50:27.0&createTime=2018-09-07 16:12:07.0&updateBy=马明&progressMark=4&id=29a6d45e9e0a45d68ae44594ea2a0835&userType=1&evaluateNum=4";
        String resStr = httpsRequest(url, "GET", null);
        System.out.println("resStr====" + resStr);
        //返回json样例：{"result":"success"}(成功)
        //			 {"result":"fail"}(失败)
        //			 {"result":"token_error"}(token错误)
    }
}